﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class CameraManager : MonoBehaviour
{

    public Transform followedCharacterTransform;

    protected Vector3 targetPosition;
    protected Vector3 lastTargetPosition;
    protected float cameraMoveDuration = 0.3f;
    protected Vector3 currentCameraSpeed;
    protected int oldDirection = 1;
    protected int direction = 1;
    protected Vector3 offset = new Vector3(4,0,0);
    protected float lookAt;
    protected Coroutine setCameraOffset;
    protected Vector3 currentSpeed;


    private void Awake()
    {
        followedCharacterTransform = GameObject.Find("player").transform;
    }

    private void Start()
    {
        lookAt = followedCharacterTransform.position.y;

        targetPosition = (followedCharacterTransform.position + direction * offset) - transform.position;

        if (targetPosition.x == 0 && targetPosition.y == 0) return;

        follow();

        targetPosition = followedCharacterTransform.position;

        oldDirection = direction = 1;

        lastTargetPosition = followedCharacterTransform.position;
    }

    public void LateUpdate()
    {    
        targetPosition = followedCharacterTransform.position - lastTargetPosition;

        if (targetPosition.x == 0 && targetPosition.y == 0) return;

        oldDirection = direction;

        if (targetPosition.x > 0) direction = 1;
        else if (targetPosition.x < 0) direction = -1;

        follow();

        lastTargetPosition = followedCharacterTransform.position;
    }

    protected void follow()
    {
        if (oldDirection != direction)
        {
            if (setCameraOffset != null)
                StopCoroutine(setCameraOffset);
            setCameraOffset = StartCoroutine("setOffset", direction);
        }
        transform.position += new Vector3(targetPosition.x, targetPosition.y, 0);
        //transform.position =  Vector3.SmoothDamp(transform.position, new Vector3(followedCharacterTransform.position.x/* + offset.y * 2 * direction*/, followedCharacterTransform.position.y,transform.position.z), ref currentSpeed, 0.1f);
        //transform.position += Vector3.Lerp(Vector3.zero, targetPosition, Time.fixedDeltaTime / 0.2f);
    }

    IEnumerator setOffset(int direction)
    {
        float time = 0;
        while (time < 0.2f)
        {
            time += Time.fixedDeltaTime;
            Vector3 tmp = new Vector3(offset.x * direction + followedCharacterTransform.position.x - transform.position.x,0,0);
            transform.position += Vector3.Lerp(Vector3.zero, tmp, Time.fixedDeltaTime / 0.2f);
            yield return new WaitForFixedUpdate();
        }
    }

    public void shake(float shakeStrength)
    {

    }

}
